package com.leochan.shuniu.database.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.leochan.shuniu.database.BaseDao;
import com.leochan.shuniu.database.model.User;

public class UserDao extends BaseDao<User> {

	private static final String TableName = "user";
	public static final String Username = "username";
	public static final String Password = "password";
	public static final String Token = "token";
	public static final String Secret = "secret";
	private static final String CREATE_USER_TABLE = String
			.format("create table %s (_id integer primary key autoincrement, %s text ,%s text, %s text, %s text)",
					TableName, Username, Password, Token, Secret);

	public UserDao(SQLiteDatabase db) {
		super(db);
	}

	@Override
	protected String getTableName() {
		return TableName;
	}

	@Override
	protected ContentValues model2ContentValues(User model) {
		ContentValues cv = new ContentValues();
		cv.put(Username, model.getUserName());
		cv.put(Password, model.getPassword());
		cv.put(Token, model.getToken());
		cv.put(Secret, model.getSecret());
		return cv;
	}

	@Override
	protected User cursor2Model(Cursor cursor) {
		if (cursor.isBeforeFirst() || cursor.isAfterLast())
			return null;
		User user = new User();
        int index;

        index = cursor.getColumnIndex(getKeyName());
        user.setId(cursor.getLong(index));

        index = cursor.getColumnIndex(Username);
        user.setUserName(cursor.getString(index));

        index = cursor.getColumnIndex(Password);
        user.setPassword(cursor.getString(index));

        index = cursor.getColumnIndex(Token);
        user.setToken(cursor.getString(index));

        index = cursor.getColumnIndex(Secret);
        user.setSecret(cursor.getString(index));
        
		return user;
	}

	@Override
	protected String createTableSql() {
		return CREATE_USER_TABLE;
	}

	@Override
	protected Object getWriteLock() {
		return UserDao.class;
	}

}
